package com.cv.system.controller.audit.captcha;

import cn.hutool.core.util.StrUtil;
import com.cv.framework.common.utils.servlet.ServletUtil;
import com.cv.framework.operatelog.core.annotations.OperateLog;
import com.xingyuv.captcha.model.common.ResponseModel;
import com.xingyuv.captcha.model.vo.CaptchaVO;
import com.xingyuv.captcha.service.CaptchaService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;

/**
 * 客服审核平台 - 验证码
 *
 * @author Charles_XDXD
 */
@Tag(name = "客服审核平台 - 验证码")
@RestController("auditCaptchaController")
@RequestMapping("/system/captcha")
public class AuditCaptchaController {

    @Resource
    private CaptchaService captchaService;

    @PostMapping({"/get"})
    @Operation(summary = "获得验证码")
    @PermitAll
    @OperateLog(enable = false)
    public ResponseModel get(@RequestBody CaptchaVO data, HttpServletRequest request) {
        assert request.getRemoteHost() != null;
        data.setBrowserInfo(getRemoteIp(request));
        return captchaService.get(data);
    }

    @PostMapping("/check")
    @Operation(summary = "校验验证码")
    @PermitAll
    @OperateLog(enable = false)
    public ResponseModel check(@RequestBody CaptchaVO data, HttpServletRequest request) {
        data.setBrowserInfo(getRemoteIp(request));
        return captchaService.check(data);
    }

    /**
     * 获取远程 IP
     *
     * @param request 请求
     * @return 远程 IP
     */
    public static String getRemoteIp(HttpServletRequest request) {
        String ip = ServletUtil.getClientIP(request);
        String userAgent = request.getHeader("user-agent");

        if (StrUtil.isNotBlank(ip)) {
            return ip + userAgent;
        }

        return request.getRemoteAddr() + userAgent;
    }

}
